package com.example.homework07.DataStorage;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.homework07.R;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Shared extends Fragment {
    String FILE_NAME= "xurilou";
    public Shared(){
        super(R.layout.shared);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EditText zhEditText = getView().findViewById(R.id.zhEditText);
        EditText mmEditText = getView().findViewById(R.id.mmEditText);
        Button button = getView().findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                android.content.SharedPreferences settings = getActivity().getSharedPreferences(FILE_NAME,Context.MODE_PRIVATE);
                android.content.SharedPreferences.Editor editor = settings.edit();
                editor.putString("zh",zhEditText.getText().toString());
                editor.putString("mm",getSHA256(mmEditText.getText().toString()));
                editor.commit();
                Toast.makeText(getActivity(),"保存成功",Toast.LENGTH_SHORT).show();
            }
        });

        android.content.SharedPreferences settings = getActivity().getSharedPreferences(FILE_NAME,Context.MODE_PRIVATE);
        String zh = settings.getString("zh","");
        String mm = settings.getString("mm","");
        zhEditText.setText(zh);
        mmEditText.setText(mm);
    }


    public static String getSHA256(String str) {
        String encodestr = "";
        try {
            MessageDigest md5 = MessageDigest.getInstance("SHA-256");
            md5.update(str.getBytes("UTF-8"));
            encodestr = byte2Hex(md5.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodestr;
    }

    private static String byte2Hex(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

}
